package com.example.service.util.service;

import com.example.common.util.enums.BusinessEnum;
import com.example.common.util.exception.BusinessException;
import com.example.common.util.exception.file.FileNameLengthLimitExceededException;
import com.example.common.util.exception.file.FileSizeLimitExceededException;
import com.example.common.util.exception.file.InvalidExtensionException;
import com.example.common.util.utils.DateUtils;
import com.example.common.util.utils.MimeTypeUtils;
import com.example.common.util.utils.StringUtils;
import com.example.service.util.properties.FilePropertiesVariable;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author juzipi
 * @Date 2021/7/20 14:32
 * @Info 还是因为读取配置文件的问题,所以它需要注入spring容器才能读取到配置
 */
@Component
public class FileUploadUtils {


    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;


    public static final String DEFAULT_BASE_DIR = "D:/file/uploadPath";


    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件
     * @throws Exception
     */
    public static final File uploadFile(MultipartFile file) throws IOException {
        try {
            //基础文件目录，文件，限制文件类型
            return uploadFile(DEFAULT_BASE_DIR, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }


    /**
     * 文件上传
     *
     * @param baseDir          相对应用的基目录
     * @param file             上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException                          比如读写文件出错时
     * @throws InvalidExtensionException            文件校验异常
     */
    public static final File uploadFile(String baseDir, MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException {
        //文件名长度
        int fileNamelength = file.getOriginalFilename().length();
        //文件名过长就抛异常,最大长度100
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }
        //校验文件大小
        assertAllowed(file, allowedExtension);
        //编码文件名
        String fileName = extractFilename(file);

        File desc = getAbsoluteFile(baseDir, fileName);
        file.transferTo(desc);
//        String pathFileName = getPathFileName(baseDir, fileName);
        return desc;
    }


    /**
     * 获取绝对路径的文件
     * @param uploadDir
     * @param fileName
     * @return
     */
    private static File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists()) {
            desc.createNewFile();
        }
        return desc;
    }


    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws InvalidExtensionException
     */
    public static final void assertAllowed(MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, InvalidExtensionException {
        //获取size
        long size = file.getSize();
        //默认50M，过大就抛异常
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
            throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取扩展？
        String extension = getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
                throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
                throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
                throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
                        fileName);
            } else {
                throw new InvalidExtensionException(allowedExtension, extension, fileName);
            }
        }

    }


    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 上传腾讯云
     * @param file
     * @return
     */
    public static String uploadCloud(MultipartFile file,String filename) {
        try {
            File uploadFile = uploadFile(file);
            PutObjectRequest putObjectRequest = new PutObjectRequest(FilePropertiesVariable.bucketName, filename, uploadFile);
            //这个是具体的保存
            COSClient cosClient = initCOSClient();
            cosClient.putObject(putObjectRequest);
            //删除
            cosClient.shutdown();
            deletedTempFile(uploadFile);
            //返回前缀加文件名就是文件路径了
            return FilePropertiesVariable.prefix+filename;
        } catch (CosClientException | IOException e) {
            e.printStackTrace();
            throw new BusinessException(BusinessEnum.FILE_UPLOAD_ERROR);
        }
    }

    /**
     * 删除本地文件
     * @param file 文件
     */
    private static void deletedTempFile(File file) {
        if (StringUtils.isNotNull(file)) {
            File delFile = new File(file.toURI());
            delFile.delete();
        }
    }


    /**
     * 删除云文件
     * @param fileName 文件名
     * @return
     */
    public static Boolean deleteCloudFile(String fileName){
        try {
            COSClient cosClient = initCOSClient();
            cosClient.deleteObject(FilePropertiesVariable.bucketName, fileName);
            cosClient.shutdown();
            return true;
        } catch (CosClientException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 初始化cos客户端
     * @return
     */
    private static COSClient initCOSClient() {
        //初始化用户身份信息
        BasicCOSCredentials basicCOSCredentials = new BasicCOSCredentials(FilePropertiesVariable.secretId, FilePropertiesVariable.secretKey);
        //设置bucket区域
        ClientConfig clientConfig = new ClientConfig(new Region(FilePropertiesVariable.bucket));
        //生成cos客户端
        return new COSClient(basicCOSCredentials, clientConfig);
    }


    /**
     * 编码文件名
     */
    public static String extractFilename(MultipartFile file) {
        String extension = getExtension(file);
        //文件名由 日期，UUID，文件后缀组成,yyt标识
        return "yyt-" + DateUtils.datePath() + "/" +UUID.randomUUID() + "." + extension;
    }


    /**
     * 获取文件名后缀
     * @param file
     * @return
     */
    private static String getExtension(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }


}
